# frozen_string_literal: true

module Vulnerabilities
  class StarboardVulnerabilityResolveService
    include Gitlab::Allowable

    REPORT_TYPE = ::Enums::Vulnerability.report_types[:cluster_image_scanning]
    STATES = Vulnerability::ACTIVE_STATES
    BATCH_SIZE = 250

    attr_reader :agent,
                :project,
                :author,
                :uuids

    def initialize(agent, uuids)
      @agent = agent
      @project = agent.project
      @author = agent.created_by_user
      @uuids = uuids
    end

    def execute
      raise Gitlab::Access::AccessDeniedError unless authorized?

      undetected.each_batch(of: BATCH_SIZE) do |batch|
        batch.update_all(resolved_on_default_branch: true, state: :resolved)
      end

      ServiceResponse.success
    end

    private

    def undetected
      project.vulnerabilities
             .with_states(STATES)
             .with_report_types(REPORT_TYPE)
             .with_findings_excluding_uuid(uuids)
             .with_cluster_agent_ids([agent.id.to_s])
    end

    def authorized?
      can?(author, :admin_vulnerability, project)
    end
  end
end
